import React, { useState } from 'react';
import Modal from '../../Modal';
import EditableText from '../../EditableText';
import { Rulebook, GameData, GameSettings, ChatMessage } from '../../../types';
import { SparklesIcon } from '../../icons';
import RulebookTuningModal from '../../PromptDiscussionModal';

interface RulebookModalProps {
  isOpen: boolean;
  onClose: () => void;
  gameData: GameData;
  settings: GameSettings;
  editableRulebook: Rulebook;
  handleRulebookEdit: (field: keyof Rulebook, value: string) => void;
  saveEditedRulebook: () => void;
  showToast: (message: string, type?: 'success' | 'error') => void;
}

const RulebookModal: React.FC<RulebookModalProps> = ({ 
    isOpen, 
    onClose, 
    gameData, 
    settings, 
    editableRulebook, 
    handleRulebookEdit, 
    saveEditedRulebook,
    showToast
}) => {
  const [isTuningModalOpen, setIsTuningModalOpen] = useState(false);
  const [editableChatHistory, setEditableChatHistory] = useState<ChatMessage[]>(gameData.rulebookChatHistory || []);
  
  const handleFinalizeTuning = (newRules: string, newHistory: ChatMessage[]) => {
    handleRulebookEdit('rules', newRules);
    setEditableChatHistory(newHistory);
    const updatedGameData = { 
        ...gameData, 
        rulebook: { ...editableRulebook, rules: newRules },
        rulebookChatHistory: newHistory 
    };
    // We don't save here, just update the state for the parent component to save on final confirmation.
    // This is a bit of a prop drilling, but necessary without a global state manager.
    // The parent `GameScreen` will handle the actual saving via `saveEditedRulebook`.
    setIsTuningModalOpen(false);
  };
  
  return (
    <>
    <Modal
      isOpen={isOpen}
      onClose={onClose}
      title="编辑游戏规则与故事"
      footer={
        <div className="flex justify-end space-x-2">
          <button onClick={onClose} className="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-md">取消</button>
          <button onClick={() => {
              // Before saving, we also need to update the gameData in the parent with the latest chat history
              const finalData = { 
                ...gameData, 
                rulebook: editableRulebook, 
                rulebookChatHistory: editableChatHistory 
              };
              // The `saveEditedRulebook` in GameScreen should use this updated data logic.
              saveEditedRulebook();
          }} className="px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white rounded-md">保存规则与故事</button>
        </div>
      }
    >
      <div className="space-y-4">
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-1">游戏名称</label>
          <EditableText initialValue={editableRulebook.gameName} onSave={(val) => handleRulebookEdit('gameName', val)} inputClassName="bg-gray-700 text-gray-100 p-2 rounded w-full" />
        </div>
        <div>
          <label className="block text-sm font-medium text-gray-300 mb-1">背景设定</label>
          <EditableText isTextArea initialValue={editableRulebook.backgroundStory} onSave={(val) => handleRulebookEdit('backgroundStory', val)} inputClassName="bg-gray-700 text-gray-100 p-2 rounded w-full min-h-[100px]" />
        </div>
        <div>
            <div className="flex justify-between items-center mb-1">
                <label className="block text-sm font-medium text-gray-300">游戏规则书</label>
                <button 
                    onClick={() => setIsTuningModalOpen(true)}
                    className="flex items-center gap-1 text-xs px-2 py-1 bg-sky-600 hover:bg-sky-700 rounded-md text-white transition-colors"
                    title="与AI讨论优化"
                >
                    <SparklesIcon className="w-4 h-4" />
                    <span>AI协助编写</span>
                </button>
            </div>
          <EditableText isTextArea initialValue={editableRulebook.rules} onSave={(val) => handleRulebookEdit('rules', val)} inputClassName="bg-gray-700 text-gray-100 p-2 rounded w-full min-h-[150px]" />
        </div>
      </div>
    </Modal>
    {isTuningModalOpen && (
        <RulebookTuningModal
            isOpen={isTuningModalOpen}
            onClose={() => setIsTuningModalOpen(false)}
            initialRules={editableRulebook.rules}
            initialChatHistory={editableChatHistory}
            gameName={editableRulebook.gameName}
            backgroundStory={editableRulebook.backgroundStory}
            settings={settings}
            showToast={showToast}
            onFinalize={handleFinalizeTuning}
        />
    )}
    </>
  );
};

export default RulebookModal;